package com.example.userservice.kafka;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.commom.enums.StatusCodeEnum;
import com.example.commom.exception.CustomException;
import com.example.commom.global.AppVariable;
import com.example.commom.global.KafkaConstants;
import com.example.feign.entity.User;
import com.example.userservice.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.transaction.annotation.Transactional;


/**
 *  处理取关/关注 主题的 kafka 消费者
 */
@Slf4j
@Configuration
@Transactional
public class KafkaFollowCustomer {

    @Autowired
    private UserService userService;

    @KafkaListener(topics = KafkaConstants.KAFKA_USER_FOLLOW_TOPIC, groupId = KafkaConstants.KAFKA_GROUP_ID)
    public void receiveInsertComment(String message, Acknowledgment acknowledgment) {

        try {

            log.info("收到消息: " + message);

            String[] strings = message.split(":");

            // 要关注的 用户id
            long followUserId = Long.parseLong(strings[0]);
            // true: 关注, false: 取关
            boolean flag = Boolean.parseBoolean(strings[1]);
            // 登录用户的Id
            long userId = Long.parseLong(strings[2]);

            LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(User::getUserId, followUserId);

            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getUserId, userId);

            if (flag) {
                // 关注, 将用户的粉丝数 +1
                lambdaUpdateWrapper.setSql("fans_count = fans_count + 1");

                // 关注列表 + 1
                updateWrapper.setSql("follow_count = follow_count + 1");


            } else {
                // 取关, 将用户粉丝 -1
                lambdaUpdateWrapper.setSql("fans_count = fans_count - 1");

                // 关注列表 - 1
                updateWrapper.setSql("follow_count = follow_count - 1");
            }

            boolean update = userService.update(lambdaUpdateWrapper);
            boolean success = userService.update(updateWrapper);

            if (update && success) {
                // 提交偏移量.
                acknowledgment.acknowledge();
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new CustomException(e.getMessage(), StatusCodeEnum.FAILED.getCode());
        }

    }

}
